/************************************************************************
                                                                     
   Xceed Ultimate ListBox for Silverlight                                                                                                                                            
   Copyright (C) 2010 Xceed Software Inc.    
                                                                     
   This program is provided to you under the terms of the GNU General Public  
   License version 2 as published by the Free Software Foundation. 
        
   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY, without even the implied warranty of 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License along 
   with this program, if not, write to the Free Software Foundation, Inc., 
   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

   This program can be provided to you by Xceed Software Inc. under a
   proprietary commercial license agreement for use in non-Open Source
   projects. Visit Xceed.com to find the commercial edition of 
   Xceed Ultimate ListBox for Silverlight.                                    
                                                                      
 **********************************************************************/

using System;
using System.Collections;
using System.ComponentModel;
using System.Linq;
using Xceed.Silverlight.Data;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Xceed.Silverlight.ListBox
{
  public class GroupDataContext : INotifyPropertyChanged
  {
    internal GroupDataContext( DataPath dataPath, ObservableCollection<GroupDescription> groupDescriptions )
    {
      if( dataPath == null )
        throw new ArgumentNullException( "dataPath" );

      if( groupDescriptions == null )
        throw new ArgumentNullException( "groupDescriptions" );

      m_dataPath = dataPath;
      m_groupDescriptions = groupDescriptions;

      this.BuildGroupValueDescriptionList();
    }

    #region DataPath Read-Only Internal Property

    internal DataPath DataPath
    {
      get
      {
        return m_dataPath;
      }
    }


    #endregion

    #region GroupValue Read-Only Property

    public object GroupValue
    {
      get
      {
        DataPath dataPath = this.DataPath;

        if( dataPath == null )
          throw new ListBoxInternalException( "No DataPath accessible for a GroupDataContext." );

        return dataPath.LastChild.Data;
      }
    }

    #endregion

    #region LeafValue Read-Only Property
    public object LeafValue
    {
      get
      {
        if( this.FieldNameValuePairs == null )
          throw new ListBoxInternalException( "FieldNameValuePairs is null." );

        return this.FieldNameValuePairs.Last().Value;
      }
    }
    #endregion

    #region RootValue Read-Only Property
    public object RootValue
    {
      get
      {
        if( this.FieldNameValuePairs == null )
          throw new ListBoxInternalException( "FieldNameValuePairs is null." );

        return this.FieldNameValuePairs.First().Value;
      }
    }
    #endregion

    #region FieldNameValuePairs Read-Only Property
    public List<FieldNameValuePair> FieldNameValuePairs
    {
      get
      {
        return m_fieldNameValuePairs;
      }
    }
    #endregion

    // Override ToString to be able to use {Binding}
    // directly in DataTemplate to display the GroupValue
    public override string ToString()
    {
      object groupValue = this.GroupValue;

      return (groupValue == null)
        ? string.Empty
        : groupValue.ToString();
    }

    #region Private Methods

    private IEnumerator GetEnumerator()
    {
      DataPath dataPath = m_dataPath;

      if( dataPath == null )
        throw new ListBoxInternalException( "No DataPath accessible for a GroupDataContext" );

      return dataPath.Select( this.DataItemToDataConverter ).GetEnumerator();
    }

    private object DataItemToDataConverter( DataItem dataItem )
    {
      if( dataItem == null )
        return null;

      // Return null if not loaded to avoid displaying
      // invalid data in async scenarios
      if( !dataItem.IsLoaded )
        return null;

      return dataItem.Data;
    }

    void BuildGroupValueDescriptionList()
    {
      m_fieldNameValuePairs = new List<FieldNameValuePair>();

      // Get the DataPath group values
      IEnumerator enumerator = this.GetEnumerator();

      if( enumerator == null )
        throw new ListBoxInternalException( "Enumerator is null." );

      // Fill the value List
      int groupDescriptionIndex = 0;
      object value = null;
      string fieldName = null;
      FieldNameValuePair groupValue = null;

      // Process each group value
      while( enumerator.MoveNext() )
      {
        if( ( groupDescriptionIndex < 0 ) || ( groupDescriptionIndex >= m_groupDescriptions.Count ) )
          break;

        value = enumerator.Current;

        // Find the associate group description field name
        fieldName = m_groupDescriptions.ElementAt( groupDescriptionIndex ).GetPropertyName();

        // Create the FieldNameValuePair
        groupValue = new FieldNameValuePair( value, fieldName );

        // Identify leaf and root GroupValue 
        // We need two different condition here (no else) because
        // a groupValue can be a Leaf and a root at the same time.
        if( groupDescriptionIndex == 0 )
        {
          groupValue.IsRoot = true;
        }

        if( groupDescriptionIndex == ( m_groupDescriptions.Count - 1 ) )
        {
          groupValue.IsLeaf = true;
        }

        // Add it to the list
        m_fieldNameValuePairs.Add( groupValue );
        groupDescriptionIndex++;
      }
    }

    #endregion


    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged( string propertyName )
    {
      if( propertyName == null )
        propertyName = string.Empty;

      if( this.PropertyChanged == null )
        return;

      this.PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
    }

    #endregion


    #region Private Members
    private DataPath m_dataPath;
    private List<FieldNameValuePair> m_fieldNameValuePairs;
    private ObservableCollection<GroupDescription> m_groupDescriptions;
    #endregion

  }
}
